import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Form, Input, Select, Button, DatePicker, Modal, message
} from 'antd';
import PTable from "../../../components/Pro/PTable";
import * as ajax from "../../../services/api";
import moment from "moment";
import InsuranceDetails from "./InsuranceDetails";


const { Option } = Select;
const { RangePicker } = DatePicker;

const dateFormat = 'YYYY-MM-DD';


@connect(state => ({
  global: state.global
}))

@Form.create()

/**
 * 企业保险列表页
 */
export default class InsuranceBasic extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      comInsId:'00',
      visibleDetail:false,
      forceUpdate:false,
      onlineUrl:'', //购买在线保险的url
      pageParm:{
        pageSize: "10",
        pageNumber: "1",
        keyword:'',//输入框的的值
        startTime:'',//开始时间
        endTime:'',//结束时间
        buyMode:'',//选择框的下拉值
      },
      keyword:'',//输入框的的值
      startTime:'',//开始时间
      endTime:'',//结束时间
      buyMode:'',//选择框的下拉值
    };
  }

  componentDidMount() {
    //初始化参数，修复页面切换参数不会初始化的bug！！
    this.ajaxInsPage();
    this.messageOnline();
  }

  //时间选择
  onChangeTime = (date, dateString) =>{
    // console.log('获得的日期>>>>>>>>>>>>>',dateString);
    this.setState({startTime:dateString[0],endTime:dateString[1] });
  };

  //输入框的模糊查询关键字
  inputTracknameChange = (e) => {
    // console.log('获得的模糊查询>>>>>>>>>>>>>',e.target.value.trim());
    this.setState({keyword: e.target.value.trim()});
  };

  //购买方式，下拉框的选择
  handleChangeBuy = (value) => {
    console.log(`selected ${value}`);
    this.setState({ buyMode:value });
  };

  //在线购买保险的链接生成
  messageOnline = () => {
    ajax.getOnlineInsBlbLink({
      comId:  this.props.global.companyInfo.comId,
    }).then((data) => {
      this.setState({
        onlineUrl:data.data,
      });
    });
  };

  //重置查询条件
  resetQueryCond =() =>{
    this.setState({
      keyword:'',//输入框的的值
      startTime:'',//开始时间
      endTime:'',//结束时间
      buyMode:'',//选择框的下拉值
      pageParm:{
        pageSize: "10",
        pageNumber: "1",
        keyword:'',//输入框的的值
        startTime:'',//开始时间
        endTime:'',//结束时间
        buyMode:'',//选择框的下拉值
      },
      forceUpdate: true,
    },
    () => {
      this.ajaxInsPage();
    });
  };

  //企业保险查询分页 点击搜索
  ajaxInsPage = () => {
    const state = {...this.state};
    const pageParm = {...this.state.pageParm};
    pageParm.buyMode = state.buyMode;
    pageParm.startTime = state.startTime;
    pageParm.endTime = state.endTime;
    pageParm.keyword = state.keyword;
    // console.log(">>>>>>>>>>>>>>>>>>>",pageParm);
    this.setState({ pageParm, forceUpdate:true}, () => {
      this.setState({forceUpdate: false});
    });
  };

  //查看在线保单内容
  queryInsDetail = (comInsId,blbOrderId) =>{
    ajax.getOnlineInsBlbDetailLink({
      comInsId,
      orderId: blbOrderId
    }).then((data)=>{
        window.open(data.data);
    },(err)=>{
        message.warning("获取在线保险详情链接失败，",err);
    });
  }

  //删除保险订单，行按钮时间
  handleDeleteList = (orderId,time) => {
    const d = new Date();
    const nowTime = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
    const lateTime = time;

    const nowTimes = nowTime.replace(/-/g,'/');
    const lateTimes = lateTime.replace(/-/g,'/');

    const a = (Date.parse(nowTimes) - Date.parse(lateTimes)) / 3600 / 1000;

    if(a <= 0){ //比较时间
      Modal.confirm({
        title: '该条保险购买记录尚在有效期内，是否确认删除该条记录',
        okText: '确认',
        cancelText:'取消',
        onOk: () => {
          ajax.comInsDeleteComInsUnderline({
            comInsId:orderId
          }).then((data) => {
            // message.success(data.msg);
            this.ajaxInsPage();
          }, (err) => {
            // message.error(err);
          });
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    }else{
      Modal.confirm({
        title: '删除后该保险购买记录不可找回，是否确认删除该条记录。确认后删除购买记录.',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          ajax.comInsDeleteComInsUnderline({
            comInsId:orderId
          }).then((data) => {
            message.success(data.msg);
            this.ajaxInsPage();
          }, (err) => {
            message.error(err);
          });
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    }
  };

  callback = () =>{
    this.setState({visibleDetail:false});
    // this.ajaxInsPage();
    this.setState({forceUpdate: true});
  };

  //表格渲染
  renderOrderList = () => {
    const columns = [
      {
        title: '保险产品名称',
        dataIndex: 'productName',
        key: 'productName',
      },
      {
        title: '在保人数',
        dataIndex: 'perNum',
        key: 'perNum',
      },
      {
        title: '购买方式',
        dataIndex: 'buyMode_name',
        key: 'buyMode_name'
        // render: (text, record) => (
        //   <div>
        //     {record.buyMode === "1" ? <span>在线购买</span> :
        //       <span>线下购买</span>}
        //   </div>
        // )
      },
      {
        title: '有效期',
        dataIndex: 'effectDate',
        key: 'effectDate',
      },
      {
        title: '保险公司',
        dataIndex: 'insComName',
        key: 'insComName',
      },
      {
        title: "操作",
        render: (text, record) => (
          <div>
            {record.buyMode === "1"
            ? //1在线购买
            <div>
              <a style={{ color:'#0f71ff' }} onClick={this.queryInsDetail.bind(this,record.comInsId, record.blbOrderId)}>查看</a>
            </div>
            : //2线下购买
            <div>
              <span style={{color: "#0f71ff", cursor: "pointer", marginRight: "20px"}}
                    onClick={() => {
                      // this.props.props.history.push(`/enterprise/company/insurance/${record.comInsId}`);
                      this.setState({
                        comInsId:record.comInsId,
                        visibleDetail:true
                      });
                    }}
              >修改</span>
              <span style={{color: "#0f71ff", cursor: "pointer"}}
                    onClick={this.handleDeleteList.bind(this, record.comInsId, record.effectEndDate)}
              >删除</span>
            </div>}
          </div>
        )
      },
    ];

    // const tmp = this.state.listPage.map((val, i) => {
    //   const value = val;
    //   value.key = i + 1;
    //   return value;
    // });

    return (
      <PTable
        // dataSource={tmp}
        // pagination={pageInitStudent}
        columns={columns}
        url="comInsGetComInsPage"
        pageParm={this.state.pageParm}
        forceUpdate={this.state.forceUpdate}
        showTotal={total => `共搜索到${total}条记录`}
      />
    );

  };

  render() {
    // const { getFieldDecorator } = this.props.form;
    let display = {display:"block"};
    if(this.state.visibleDetail){
      display = {display:"none"};
    }

    return (
      <div>
        <div className="Insurance" style={display}>
          <div className="form">
            <label>关键字：
              <Input style={{width: 214}}
                    placeholder="请输入保险名称/保险公司名称"
                    onChange={this.inputTracknameChange}
                    value={this.state.keyword}
                    maxLength="20"
              /></label>
            <label style={{marginLeft:16}}>购买方式：
              <Select style={{ width: 120 }} value={this.state.buyMode} onChange={this.handleChangeBuy} placeholder="请选择">
                <Option value="">全部</Option>
                <Option value="1">在线购买</Option>
                <Option value="2">线下购买</Option>
              </Select>
            </label>
            <label style={{marginLeft:16}}>起保日期：
               <RangePicker
                format={dateFormat}
                onChange={this.onChangeTime}
                value={[
                  this.state.startTime === '' ? null : moment(this.state.startTime, dateFormat),
                  this.state.endTime === '' ? null : moment(this.state.endTime, dateFormat)
                ]}
              />
            </label>
            <Button style={{marginLeft:16}} type="primary" onClick={this.ajaxInsPage}>搜索</Button>
            <Button style={{marginLeft:16}} onClick={this.resetQueryCond}>重置</Button>
          </div>
          <div className="btnbox" style={{ marginTop:'16px' }}>
            <Button type="primary" onClick={() => {
              // this.props.props.history.push(`/enterprise/company/insurance/${'00'}`);
              this.setState({
                comInsId:'00',
                visibleDetail:true
              });
            }}>
              新增线下保险记录
            </Button>
            <Button onClick={() => {
              window.open(this.state.onlineUrl);
            }}>购买在线保险</Button>
          </div>
          {this.renderOrderList()}
        </div>
        {this.state.visibleDetail && <InsuranceDetails comInsId={this.state.comInsId} close={this.callback} visible={this.state.visibleDetail} />}
      </div>
    );
  }
}
